define(function(require, exports, module) {
	"require:nomunge,exports:nomunge,module:nomunge";
var wind_async=require('ddf_wind_async');

var base=require('component-base');

var history = require('component-history');

var shopId=$("#session_shopid").val();	
var beforeEditTypeName;//更新前分类名称
var firstLoadFlag=false;

var zNodes =[],setting;




//require.async(['../../../js/zTree/js/jquery.ztree.core-3.5.js','../../../js/zTree/js/jquery.ztree.excheck-3.5.js','../../../js/zTree/js/jquery.ztree.exedit-3.5.js'],function(){
//	if(!firstLoadFlag){
//		firstLoadFlag=true;
//		loadPage();
//	}
//});

exports.init=function(m) {

	window.$ddf_merchandise_typeTree = m;
//	if(firstLoadFlag){
		loadPage();
//	}
};

function loadPage(){
	var htmlStr="";
	htmlStr += '<div id="content-header">';
	htmlStr += '<div id="breadcrumb"> <a href=javascript:$ddf_base.load("'+ddf.index.index_js+'") title="返回首页" class="tip-bottom"><i class="icon-home"></i> 首页</a><a href=javascript:$ddf_merchandise.showDiv("content0")>商品管理</a><a href="javascript:void(0)" class="current">商品分类管理</a></div>';
	htmlStr += '</div>    ';
	htmlStr += '<div class="container-fluid">';
	htmlStr += '<div class="row-fluid">';
	htmlStr += '<div class="span12">';
	
	htmlStr += '<div class="widget-box">';
	htmlStr += '<div class="widget-title">';
	htmlStr += '<span class="icon">';
	htmlStr += '<i class="icon-pencil"></i>';
	htmlStr += '</span>';
	htmlStr += '<h5>管理商品分类</h5>';
	htmlStr += '</div>';
	htmlStr += '<div class="widget-content"> ';
	htmlStr += '<div class="div-btn" id="buttonBox">            ';
	htmlStr += '<button class="btn btn-warning" id="addMerchandiseBtn" type="button" onclick=$ddf_merchandise_typeTree.showAddMerTypePage("","")>新增一级分类</button>';
	htmlStr += ' <button id="saveSortBtn" style="display:none" class="btn btn-success" id="addMerchandiseBtn" type="button" onclick=$ddf_merchandise_typeTree.getSortAfterNodes()>保存商品分类排序</button>';
	htmlStr += '</div>';
	htmlStr += '</div>';
	htmlStr += '</div>    ';
	
	htmlStr += '<div class="widget-box">';
	htmlStr += '<div class="widget-title">';
	htmlStr += '<span class="icon">';
	htmlStr += '<i class="icon-pencil"></i>';
	htmlStr += '</span>';
	htmlStr += '<h5>商品分类</h5>';
	htmlStr += '</div>';
	htmlStr += '<div class="widget-content"> ';
	htmlStr += '<div id="merchandiseTypeZTree">';
	
	
	htmlStr += '<div class="content_wrap">';
	htmlStr += '<div class="zTreeDemoBackground left">';
	htmlStr += '<ul id="merTypeTree" class="ztree"></ul>';
//	htmlStr += '<br/>';
//	htmlStr += '<a href="#" onclick=$ddf_merchandise_typeTree.addMerchandiseType("","")>新增一级分类</a>';
	//<ul class="zTreeDragUL ztree" id="merTypeTree_15_ul_tmp" style="top: 349px; left: 331px;"><li id="merTypeTree_15_tmp" style="padding: 0px;"><a title="家政服务" style="" target="_blank" onclick="" treenode_a="" class="level0" id="merTypeTree_15_a"><span style="" class="button ico_close" treenode_ico="" title="" id="merTypeTree_15_ico"></span><span id="merTypeTree_15_span">家政服务</span></a></li></ul>
	//<span id="zTreeMove_arrow_tmp" class="tmpzTreeMove_arrow" style="display: block; top: 355.833px; left: 283.917px;"></span>
	
	
	htmlStr += '<div>';
	htmlStr += '<div id="divSortContent"></div>';
	htmlStr += '</div>';
	
	htmlStr += '</div>';
	htmlStr += '</div>';

	
	htmlStr += '</div>';		
	htmlStr += '</div>';
	htmlStr += '</div>    ';
	
	htmlStr += '</div>';
	htmlStr += '</div>';
	htmlStr += '</div>';
//	
	showDiv("content0");
	
	$("#content0").html(htmlStr);
	
	
	getMerchandiseTypeList();
	
	$(document).ready(function(){
		$.fn.zTree.init($("#merTypeTree"), setting,zNodes);
	}); 
	
	
}



function getMerchandiseTypeList(){
	
	setting = {	
			data: {
				simpleData: {
					enable: true,
					idKey:"id",		//主键标识
					pIdKey:"pid",	//父级ID标识
				}
			},
			async: {
				enable: true,
				url:CTX+"/shopadmin/Merchandise/getMerchandiseTypeList.do",
				type:"post",
				dataFilter: filter	//异步提交回调函数
			},
			view: {
				addHoverDom: addHoverDom,	
				removeHoverDom: removeHoverDom,
				addDiyDom: addDiyDom,
				selectedMulti: false
			},
			edit: {
				drag: {
					autoExpandTrigger: true,
					prev: dropPrev,
					inner: dropInner,
					next: dropNext
				},
				enable: true,
				editNameSelectAll: true,
				showRemoveBtn: showRemoveBtn,	//父节点不显示删除图标
				showRenameBtn: true,	//是否显示修改图标（默认都显示）
				renameTitle:"修改分类",
				removeTitle:"删除分类",
			},
			
			callback: {
				beforeEditName: beforeEditName,	//进入修改节点名称前
				beforeRename: beforeRename,		//修改节点前
				onRename: onRename,				//修改节点
				beforeRemove: beforeRemove,		//删除节点前
//				onRightClick: OnRightClick,		//右击出现菜单
				beforeDrag: beforeDrag,			//拉起节点前
				beforeDrop: beforeDrop,			//放下节点前
				beforeDragOpen: beforeDragOpen,	//目标节点是否自动打开
				onDrag: onDrag,					//拉起节点
				onDrop: onDrop,					//放下节点
				onExpand: onExpand
			}
	};
	
//	setTimeout(function(){$.fn.zTree.init($("#merTypeTree"), setting,zNodes);},500);

}

function filter(treeId, parentNode, childNodes) {
	var array = [];
	if (!childNodes) return null;
	for (var i=0, l=childNodes.merchandiseTypeList.length; i<l; i++) {
		
		repname = childNodes.merchandiseTypeList[i].MERCHANDISE_TYPE_NAME.replace(/\.n/g, '.');

		array[i] = {
				id:childNodes.merchandiseTypeList[i].MERCHANDISE_TYPE_ID,
				name:repname,
				pid:childNodes.merchandiseTypeList[i].PARENT_ID,
				merNum:childNodes.merchandiseTypeList[i].merNum,
			};
		
	}
	return array;
}

//进入修改分类名称状态前
function beforeEditName(treeId, treeNode) {
	beforeEditTypeName = treeNode.name;
	var zTree = $.fn.zTree.getZTreeObj("merTypeTree");
	zTree.selectNode(treeNode);
	return true;
}

//修改分类名称前
function beforeRename(treeId, treeNode, newName, isCancel) {
	if (newName.length == 0) {
		alert("节点名称不能为空.");
		var zTree = $.fn.zTree.getZTreeObj("merTypeTree");
		setTimeout(function(){zTree.editName(treeNode);}, 10);
		zTree.cancelEditName();
		return false;
	}
	return true;
}

//修改分类名称
function onRename(e, treeId, treeNode, isCancel) {
	
	if(beforeEditTypeName === treeNode.name){//判断分类名称是否有改变
		return;
	}else{
		isCancel=true;
	}
	
	confirm("是否确定将分类“" + beforeEditTypeName + "”的名称改为“" + treeNode.name + "”？") ? isCancel=true:isCancel=false;//判断用户确定是否修改
	
	if(isCancel){
		var params={
			"merchandiseTypeId":treeNode.id,
			"merchandiseTypeName":treeNode.name,
		};
		base.showLoading();
		eval(Wind.compile("async", function() {
			var data = $await(wind_async.DDF_AsyncRequest("POST", ddf.merchandise.updateMerchandiseType,params));
			operMerchandiseTypeCallBack(data);
			}))().start();
	}else{
		treeNode.name = beforeEditTypeName;//重置回修改前的状态
	}
}


//父节点不显示删除图标
function showRemoveBtn(treeId, treeNode) {
	return !treeNode.isParent;
}

//进入删除分类状态前
function beforeRemove(treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("merTypeTree");
	zTree.selectNode(treeNode);
	
	
	if(!confirm("是否确定删除分类：“" + treeNode.name + "”？")){//判断用户确定是否删除
		return false;
	}

	if(treeNode.merNum>0){
		base.tips_error("该商品分类已被商品关联，不允许删除");
		return false;
	}
	
	var params={
		"merchandiseTypeId":treeNode.id,
		"operType":"checkMerNum",
	};
	
	base.showLoading();
	eval(Wind.compile("async", function() {
		var data = $await(wind_async.DDF_AsyncRequest("POST", ddf.merchandise.deleteMerchandiseType,params));
		base.cancelLoading();
		
//		if(!data["merNum"]){
//			base.tips_error("该商品分类已被商品关联，不允许删除");
//			
//		}else{
			
			zTree.removeNode(treeNode);
			var params={
					"merchandiseTypeId":treeNode.id,
				};
				
				base.showLoading();
				eval(Wind.compile("async", function() {
					var data = $await(wind_async.DDF_AsyncRequest("POST", ddf.merchandise.deleteMerchandiseType,params));
					operMerchandiseTypeCallBack(data);
				}))().start();

//		}
		
	}))().start();
	
	return false;
}


//操作分类回调函数
function operMerchandiseTypeCallBack(data){
	if (data["code"] == "1") {
		base.tips(data["message"]);
	} else {
		base.tips_error(data["message"]);
	}
	base.cancelLoading();
}

//自定义属性标签
function addDiyDom(treeId, treeNode) {
	var aObj = $("#" + treeNode.tId + "_a");
	if ($("#diyBtn_"+treeNode.tId).length>0) return;
	var editStr = "<span id='diyBtn_space_" +treeNode.tId+ "' style='font-size:10px; color:#999999' >（商品：<q id=merNumSpan"+treeNode.tId+" style='font-size:10px; color:#999999'>"+treeNode.merNum+"</q>）</span>";
	aObj.append(editStr);
};

function addHoverDom(treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("merTypeTree");
	var sObj = $("#diyBtn_space_" + treeNode.tId);
	if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
	var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
		+ "' title='添加分类' onfocus='this.blur();'></span>";

	if(treeNode.level==0){//父级菜单
		sObj.after(addStr);
	}
	
	var btn = $("#addBtn_"+treeNode.tId);
	if (btn) btn.bind("click", function(){

		exports.showAddMerTypePage(treeNode.tId,treeNode.id);
		
		return false;
	});
	
};


exports.addMerchandiseType=function(treeNodeTId,parentId){
	
	var merTypeName = $("#input-merchandiseTypeName").val();
	if(isNull(merTypeName)){
		
		base.tips_error("商品分类名非法");
		
		return;
	}
	base.showLoading();
	var params={
			"merchandiseTypeName":merTypeName,
			"parentId":parentId
	        };
	

	eval(Wind.compile("async",function(){
			
			var data = $await(wind_async.DDF_AsyncRequest("POST",ddf.merchandise.addMerchandiseType,params));
			
			if(data["code"]=="1"){
				base.tips("添加分类成功");
				var zTree = $.fn.zTree.getZTreeObj("merTypeTree");
				var parentNode = zTree.getNodeByTId(treeNodeTId);
				zTree.addNodes(parentNode, {id:data["merchandiseTypeId"], pId:parentId, name:merTypeName ,merNum:0});
				zTree.cancelSelectedNode();
			}else{
				base.tips_error(data["message"]);
			}
			base.cancelLoading();
		}))().start();
};

function dropPrev(treeId, nodes, targetNode) {
	var pNode = targetNode.getParentNode();
	if (pNode && pNode.dropInner === false) {
		return false;
	} else if(curDragNodes[0].isParent && targetNode.level===1){ 
		return false; 
	} else {
		for (var i=0,l=curDragNodes.length; i<l; i++) {
			var curPNode = curDragNodes[i].getParentNode();
			if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
				return false;
			}
		}
	}
	return true;
}
function dropInner(treeId, nodes, targetNode) {
	if (targetNode && targetNode.dropInner === false) {
		return false;
	} else if(targetNode && targetNode.level>0){ 
		return false; 
	} else if(curDragNodes[0].isParent){ 
		return false; 
	} else {
		for (var i=0,l=curDragNodes.length; i<l; i++) {
			if (!targetNode && curDragNodes[i].dropRoot === false) {
				return false;
			} else if (curDragNodes[i].parentTId && curDragNodes[i].getParentNode() !== targetNode && curDragNodes[i].getParentNode().childOuter === false) {
				return false;
			}
		}
	}
	return true;
}
function dropNext(treeId, nodes, targetNode) {
	var pNode = targetNode.getParentNode();
	if (pNode && pNode.dropInner === false) {
		return false;
	} else if(curDragNodes[0].isParent && targetNode.level===1){ 
		return false; 
	} else {
		for (var i=0,l=curDragNodes.length; i<l; i++) {
			var curPNode = curDragNodes[i].getParentNode();
			if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
				return false;
			}
		}
	}
	return true;
}
var log, className = "dark", curDragNodes, autoExpandNode,beforeNodeParent, isOneToSecond;
function beforeDrag(treeId, treeNodes) {
	className = (className === "dark" ? "":"dark");
//	showLog("[ "+getTime()+" beforeDrag ]&nbsp;&nbsp;&nbsp;&nbsp; drag: " + treeNodes.length + " nodes." );
	for (var i=0,l=treeNodes.length; i<l; i++) {
		if (treeNodes[i].drag === false) {
			curDragNodes = null;
			return false;
		} else if (treeNodes[i].parentTId && treeNodes[i].getParentNode().childDrag === false) {
			curDragNodes = null;
			return false;
		}
	}
	curDragNodes = treeNodes;
	beforeNodeParent = null;
	isOneToSecond = false;
	if(treeNodes[0].level ==0 && !treeNodes[0].isParent){
		beforeNodeParent=treeNodes[0];
		isOneToSecond = true;
	}else if(treeNodes[0].level !=0){
		beforeNodeParent=treeNodes[0].getParentNode();//记录拖拽前的父级分类对象
	}
	return true;
}
function beforeDragOpen(treeId, treeNode) {
	autoExpandNode = treeNode;
	return true;
}
function beforeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {
	className = (className === "dark" ? "":"dark");

	if(targetNode==null){
		return false;
	}
	
//	if((treeNodes[0].merNum>0 || treeNodes[0].barcodeNum>0) && treeNodes[0].level==1 && targetNode.level!=1  && moveType!="inner"){	//关联商品数大于0，且是二级分类，则不能移动到一级分类
//		base.tips_error("该分类已有关联商品，不能成为一级分类");
//		return false;
//	}
	
	if(beforeNodeParent!=null){
		if(!isOneToSecond){
		
			//将移动分类前的父级分类的关联商品（标准商品）数目 减去 移动分类的管理商品（标准商品）数目
			beforeNodeParent.merNum = parseInt(beforeNodeParent.merNum) - parseInt(treeNodes[0].merNum);
			$("#merNumSpan"+beforeNodeParent.tId).html(beforeNodeParent.merNum);
			
		}
		if(targetNode.level==0){//当目标分类的是父级时
			if(moveType=="inner"){
				targetNode.merNum = parseInt(targetNode.merNum) + parseInt(treeNodes[0].merNum);
				$("#merNumSpan"+targetNode.tId).html(targetNode.merNum);
			}
		}else{
			targetNode.getParentNode().merNum = parseInt(targetNode.getParentNode().merNum) + parseInt(treeNodes[0].merNum);
			$("#merNumSpan"+targetNode.getParentNode().tId).html(targetNode.getParentNode().merNum);
		}
		
	}
	
	
	return true;
}
function onDrag(event, treeId, treeNodes) {
	className = (className === "dark" ? "":"dark");
//	showLog("[ "+getTime()+" onDrag ]&nbsp;&nbsp;&nbsp;&nbsp; drag: " + treeNodes.length + " nodes." );
}
function onDrop(event, treeId, treeNodes, targetNode, moveType, isCopy) {
	$("#saveSortBtn").css("display","inline");
	className = (className === "dark" ? "":"dark");
//	showLog("[ "+getTime()+" onDrop ]&nbsp;&nbsp;&nbsp;&nbsp; moveType:" + moveType);
//	showLog("target: " + (targetNode ? targetNode.name : "root") + "  -- is "+ (isCopy==null? "cancel" : isCopy ? "copy" : "move"))
}
function onExpand(event, treeId, treeNode) {
	if (treeNode === autoExpandNode) {
		className = (className === "dark" ? "":"dark");
//		showLog("[ "+getTime()+" onExpand ]&nbsp;&nbsp;&nbsp;&nbsp;" + treeNode.name);
	}
}

function removeHoverDom(treeId, treeNode) {
	$("#addBtn_"+treeNode.tId).unbind().remove();
};
function selectAll() {
	var zTree = $.fn.zTree.getZTreeObj("merTypeTree");
	zTree.setting.edit.editNameSelectAll =  $("#selectAll").attr("checked");
}


exports.showAddMerTypePage=function(treeNodeTId,parentId) {
	var id = "merchandise_typeTree_js";
	var title = "添加分类";
	var info = "<div class='row-fluid'><div class='control-group'><label class='control-label'>分类名称：</label><div class='controls'><input class='span8 m-wrap' type='text' id='input-merchandiseTypeName'/></div></div></div>";
//	var href = "####";
	var btnleft = "确定";
	var btnright="取消";
	var noplayer = '<div id="' + id + '" class="modal">'
			+ '<div class="modal-header">'
			+ '<button class="close over" type="button">×</button>'
			+ '<h3>' + title + '</h3>' + '</div>'
			+ '<div class="modal-body form-horizontal">' + info 
			+ '</div>'
			+ '<div class="modal-footer"> <button class="btn over" onclick=$ddf_merchandise_typeTree.addMerchandiseType("'+treeNodeTId+'","'+parentId+'")>'+btnleft+'</button>  <button class="btn over">'+btnright+'</button> </div>'+
			+ '</div>';
	$(noplayer).appendTo("body");
	$("<div class='modal-backdrop in'></div>").appendTo("body");
	$("#" + id).find(".over").click(function() {
		$("#" + id).remove();
		$("body .modal-backdrop").remove();
	});

};

///递归遍历旗下子节点
function ForeachFindChildNode(nodes, NodeArr) {

//遍历获取每一个节点

	for (var i = 0; i < nodes.children.length; i++) {

		var node = new Object();

		node.id = nodes.children[i].id;

		node.name = nodes.children[i].name;

		node.pid = nodes.children[i].pid;

		node.sortNum = i+1;

		//将new后的新对象附加到数组内

		NodeArr.push(node);

		//判断其是否有子节点 有且进入递归查找

		if (nodes.children[i].children != null && nodes.children[i].children.length > 0) {

			ForeachFindChildNode(nodes.children[i], NodeArr);

		}

	}

}

 

///获得排序后的节点数组
exports.getSortAfterNodes=function() {
	
	var NodeArr = new Array();//定义一个数组用于存放排序后的节点信息
	
	var treeLeftObj = $.fn.zTree.getZTreeObj("merTypeTree");//获得树对象

	var nodes = treeLeftObj.getNodes();//拿到所有节点
	//遍历获取每一个节点
	for (var i = 0; i < nodes.length; i++) {
		var node = new Object();
		node.id = nodes[i].id;
		node.pid = nodes[i].pid;
		node.sortNum = i+1;
		//将new后的新对象附加到数组内
		NodeArr.push(node);
		//判断其是否有子节点 有且进入递归查找
		if (nodes[i].children != null && nodes[i].children.length > 0) {
			ForeachFindChildNode(nodes[i], NodeArr);
		}
	}
	//组后的NodeArr数组就是排序后的节点了，排序属性为sortNum
	var params = {};
	for (var i = 0; i < NodeArr.length; i++) {
		params["merchandiseTypeIdArr[" + i + "]"] = NodeArr[i].id;
		params["merchandiseTypeParentIdArr[" + i + "]"] = NodeArr[i].pid;
		params["merchandiseTypeSortArr[" + i + "]"] = NodeArr[i].sortNum;
	}
	
	base.showLoading();
	eval(Wind.compile("async", function() {
		var data = $await(wind_async.DDF_AsyncRequest("POST", ddf.merchandise.updateMerchandiseTypeSort,params));

		if(data["code"]=="1"){
			base.tips("保存分类排序成功！");
			$("#saveSortBtn").css("display","none");
		}else{
			base.tips_error(data["message"]);
		}
		base.cancelLoading();
		}))().start();
	

};

function showDiv(block) {

	$("#content > div").hide();

	if ($("#" + block).length <= 0) {

		$("#content").append('<div id="' + block + '"></div>');

	} else {

		$("#" + block).show();
	}

}


exports.showDiv = showDiv;

});